package top.roadvast.rabbitmq.provider.direct;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import lombok.extern.slf4j.Slf4j;
import top.roadvast.rabbitmq.utils.ConnectionUtil;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.TimeoutException;

/**
 * 生产者，模拟为商品服务
 */
@Slf4j
public class DirectSend {
    private final static String EXCHANGE_NAME = "direct_exchange";

    private static final List<String> OPS = Arrays.asList("insert", "update", "delete");
 
    public static void main(String[] arg) {
        // 获取到连接
        // 获取通道
        try(Connection connection = ConnectionUtil.getConnection();
            Channel channel = connection.createChannel();) {
            // 声明exchange，指定类型为direct
            channel.exchangeDeclare(EXCHANGE_NAME, "direct");
            final Scanner scanner = new Scanner(System.in);
            System.out.println("请输入要[RoutingKey]的索引值[0-insert;1-update;2-delete]：");

            while (scanner.hasNext()) {
                final int op = scanner.nextInt();
                scanner.nextLine();
                if (op >= 0 && op <= 2) {
                    System.out.println("RoutingKey = " + OPS.get(op) + " ，输入消息后按回车发送：");
                    final String msg = scanner.nextLine();

                    // 发送消息，并且指定routing key 为：insert/update/delete ,代表新增/编辑/删除
                    channel.basicPublish(EXCHANGE_NAME, OPS.get(op), null, msg.getBytes());

                    if (log.isDebugEnabled()) {
                        log.debug(" [生产者] 将消息 '" + msg + "' 发送到 [RoutingKey = " + OPS.get(op) + "] 的交换机上.");
                    }
                    System.out.println("请输入要[RoutingKey]的索引值[0-insert;1-update;2-delete]：");
                } else {
                    System.out.println("请输入要[RoutingKey]的索引值[0-insert;1-update;2-delete]：");
                }
            }
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        }
    }
}